package com.example.newjiesai.util;

import com.alibaba.fastjson.JSONObject;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

@Component
public class HttpUtil {

    private static RestTemplate restTemplate = new RestTemplate();

    public static String httpRequest(String requestUrl, String requestMethod) {
        StringBuffer buffer = new StringBuffer();
        String retStr = null;
        try {

            URL url = new URL(requestUrl);
            // http协议传输
            HttpURLConnection httpUrlConn = (HttpURLConnection) url.openConnection();

            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式（GET/POST）
            httpUrlConn.setRequestMethod(requestMethod);

            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();
            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            retStr = buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return retStr;
    }

    public static JSONObject httpRequestJSON(String requestUrl, String requestMethod) {
        JSONObject jsonObject = null;
        String buffer = httpRequest(requestUrl,requestMethod);
        jsonObject = JSONObject.parseObject(buffer.toString());
        return jsonObject;
    }


    public static String transmitAsJSON(JSONObject postDataArr, String url){


        String returnString;


        try {
            //外网地址
            //String url = "http://222.240.80.99:8890/zhongnan/uploadPosition";
            //内网地址
            //String url = "http://10.210.5.21:9024/zhongnan/uploadPosition";
            //喜讯内网接口地址
            //String url = "http://10.210.5.21:9024/LocalService/ptlap/receive.action";

            //设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.TEXT_PLAIN);
            HttpEntity<String> req = new HttpEntity<String>(postDataArr.toJSONString(),headers);

            returnString = restTemplate.postForEntity(url, req, String.class).getBody();


        }catch (Exception e){
            e.printStackTrace();
            returnString = e.toString();
        }


        return returnString;

    }

    public static String sendPost(String url, String param)
    {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性
            //注意在传送json数据时， Content-Type的值
            conn.setRequestProperty("Content-Type",
                    "application/json");
            conn.setRequestProperty("connection", "keep-alive");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.write(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }

}
